import React, {Component} from 'react'
import utils from './utils'
import RouteContext from './RouteContext'


class BrowserRouter extends Component {

  state={
    currentPath:utils.extractHashPath(window.location.href)
  }

  
  componentDidMount() {
    window.addEventListener("hashchange", this.onHashChange);
  }

  componentWillUnmount() {
    window.removeEventListener(("hashchange", this.onHashChange))
  }
  
  onHashChange=(e)=>{
    //截取路径
    const currentPath = utils.extractHashPath(e.newURL);
    console.log("onHashChange:", currentPath);  // /about
    this.setState({ currentPath });
  }


  render() {
    console.log('%c%s', 'color: #f2ceb6','window.location.href', window.location.href);

    console.log('%c%s', 'color: #00e600','onPopState', this.onPopState );
    return (
      <RouteContext.Provider value={{currentPath: this.state.currentPath, onPopState: this.onPopState}}>
        {this.props.children}
      </RouteContext.Provider>
    )
  }
}

export default BrowserRouter


